//
//  MHBlackListViewModel.m
//  MiaoCircle
//
//  Created by Xuzhengrong on 2018/5/5.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "MHBlackListViewModel.h"
//#import "MHCircleMember.h"
#import "MHBlackModel.h"

@implementation MHBlackListViewModel
- (instancetype)initWithServices:(id<MHViewModelServices>)services params:(NSDictionary *)params{
    if (self = [super initWithServices:services params:params]) {
        self.info = params[MHViewModelUtilKey];
        
    }
    return self;
}


-(void)initialize
{
    [super initialize];
    self.title = @"黑名单";
    self.shouldPullUpToLoadMore = YES;
    /// 没有数据时，隐藏底部刷新控件
    self.shouldEndRefreshingWithNoMoreData = NO;
    
    @weakify(self);
    RAC(self, blackList) = self.requestRemoteDataCommand.executionSignals.switchToLatest;
    /// 数据源
    RAC(self,dataSource) = [RACObserve(self, blackList) map:^(NSArray * blacks) {
        @strongify(self)
        MHCommonGroupViewModel *group1 = [MHCommonGroupViewModel groupViewModel];
        group1.itemViewModels = [self dataSourceWithcircleMembers:blacks];
        return blacks.count?@[group1]:@[];
    }];
    
    self.removeMemberCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSNumber  *identity ) {
        @strongify(self);
        int memberId = [identity intValue];
        return [self.services.client deleteCircleMember: memberId];
    }];
    
    self.cancelBlackMemberCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSNumber  *identity ) {
        int memberId = [identity intValue];
        return [self.services.client cancelCircleMemberBlack:memberId];
    }];

    
}

- (RACSignal *)requestRemoteDataSignalWithPage:(NSUInteger)page{
    
    NSMutableArray * (^mapcircleMembers)(NSArray *) = ^(NSArray *blacks) {
        if (page == 1) {
            /// 下拉刷新
        } else {
            /// 上拉加载
            blacks = @[(self.blackList ?: @[]).rac_sequence, blacks.rac_sequence].rac_sequence.flatten.array;
        }
        return [blacks mutableCopy];
    };
    return [[[self.services.client fetchBlackListWithCircleId:self.info.autoId pageNum:page pageSize:self.perPage] mh_parsedResults] map:mapcircleMembers];
}

#pragma mark - 辅助方法
- (NSArray *)dataSourceWithcircleMembers:(NSArray *)blackList {
    if (MHObjectIsNil(blackList) || blackList.count == 0) return nil;
    NSMutableArray *viewModels = [[blackList.rac_sequence map:^(MHBlackModel *circleMember) {
        MHCommonItemViewModel *viewModel  = [MHCommonItemViewModel itemViewModelWithTitle:circleMember.nickName   icon:circleMember.fullUserFace];
//        viewModel.subtitle = @"...  ";
        viewModel.model = circleMember;
        return viewModel;
    }].array mutableCopy];
    
    return viewModels ?: @[] ;
}

@end
